package com.yzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzg.pojo.RolePermission;
import com.yzg.service.RolePermissionService;
import com.yzg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzg.mapper.PermissionMapper;
import com.yzg.pojo.Permission;
import com.yzg.service.PermissionService;
import org.springframework.util.StringUtils;

/**
* @Author: decade
* @Description: ${description}
* @Date: 2021/1/14 20:49
**/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService{
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserService userService;
    //给角色分配权限
    @Override
    public void saveRolePermissionRealtion(String roleId, String[] permissionIds) {
        //先删除对应角色的菜单权限
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        //再添加
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for(String permissionId : permissionIds) {
            if(StringUtils.isEmpty(permissionId)) continue;
            if("0".equals(permissionId)){
                continue;
            }
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }
        //最后拼接上一级菜单
        RolePermission rolePermission1 = new RolePermission();
        rolePermission1.setRoleId(roleId);
        rolePermission1.setPermissionId("1");
        rolePermissionList.add(rolePermission1);

        rolePermissionService.saveBatch(rolePermissionList);
    }

    //根据角色获取菜单
    @Override
    public List<Permission> selectAllMenu(String roleId) {
        //CAST函数语法规则是：Cast(字段名 as 转换的类型 )
        //查询所有菜单权限
        List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));
        //根据角色id获取角色权限
        List<RolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id",roleId));
        //主要该用户的权限isSelect设置选中
        for(int i=0;i<allPermissionList.size();i++){
            Permission permission = allPermissionList.get(i);
            for(int m=0;m<rolePermissionList.size();m++){
                if(rolePermissionList.get(m).getPermissionId().equals(permission.getId())){
                    permission.setSelect(true);
                }
            }
        }
        //封装成树形
        List<Permission> permissionList = bulid(allPermissionList);
        return permissionList;
    }

    //获取所有菜单
    @Override
    public List<Permission> queryAllMenu() {
        //1 查询菜单表所有数据
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<Permission> permissionList = baseMapper.selectList(wrapper);
        //2 把查询所有菜单list集合按照要求进行多级嵌套封装,
        List<Permission> result = bulid(permissionList);
        return result;
    }

    //递归删除菜单
    @Override
    public void removeChildById(String id) {
        //1 创建list集合，用于封装所有删除菜单id值
        List<String> idList = new ArrayList<>();
        //2 向idList集合设置删除菜单id
        this.selectPermissionChildById(id,idList);
        //把当前id封装到list里面
        idList.add(id);
        baseMapper.deleteBatchIds(idList);
    }

    //2 根据当前菜单id，查询菜单里面子菜单id，封装到list集合
    private void selectPermissionChildById(String id, List<String> idList) {
        //查询菜单里面子菜单id
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", id);
        wrapper.select("id");
        List<Permission> childIdList = baseMapper.selectList(wrapper);
        //把childIdList里面菜单id值获取出来，封装idList里面，做递归查询
        childIdList.stream().forEach(item ->{
            //封装idList里面
            idList.add(item.getId());
            //递归查询
            this.selectPermissionChildById(item.getId(), idList);
        });
    }

    /**
     * 使用递归方法建菜单
     * @param treeNodes
     * @return
     */
    private static List<Permission> bulid(List<Permission> treeNodes) {
        List<Permission> trees = new ArrayList<>();

        for (Permission treeNode : treeNodes) {
            if ("0".equals(treeNode.getPid())) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    private static Permission findChildren(Permission treeNode,List<Permission> treeNodes) {
        treeNode.setChildren(new ArrayList<Permission>());

        for (Permission it : treeNodes) {
            if(treeNode.getId().equals(it.getPid())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }
}
